package com.personal.portal.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.personal.portal.common.entity.Result;
import com.personal.portal.admin.entity.DictCategory;
import com.personal.portal.admin.entity.DictItem;
import com.personal.portal.admin.mapper.DictCategoryMapper;
import com.personal.portal.admin.mapper.DictItemMapper;
import com.personal.portal.admin.service.DictCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 字典分类服务实现类
 * 
 * @author zhanghui
 * @version 1.0.0
 * @since 2025-11-10
 */
@Service
public class DictCategoryServiceImpl implements DictCategoryService {

    @Resource
    private DictCategoryMapper dictCategoryMapper;
    
    @Resource
    private DictItemMapper dictItemMapper;

    @Override
    public DictCategory queryById(Long id) {
        validateId(id);
        return dictCategoryMapper.selectOneById(id);
    }

    @Override
    public DictCategory queryByEntity(DictCategory dictCategory) {
        QueryWrapper queryWrapper = buildQueryWrapper(dictCategory);
        return dictCategoryMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public List<DictCategory> queryList(DictCategory dictCategory) {
        QueryWrapper queryWrapper = buildQueryWrapper(dictCategory);
        List<DictCategory> categories = dictCategoryMapper.selectListByQuery(queryWrapper);
        
        // 为每个分类统计字典值数量
        for (DictCategory category : categories) {
            long count = countDictItemsByCategoryId(category.getId());
            category.setItemCount(count);
        }
        
        return categories;
    }

    @Override
    public DictCategory queryByCode(String code) {
        if (StringUtils.isBlank(code)) {
            throw new IllegalArgumentException("分类代码不能为空");
        }
        
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DictCategory::getCode, code);
        DictCategory dictCategory = dictCategoryMapper.selectOneByQuery(queryWrapper);
        
        if (dictCategory != null) {
            // 统计字典值数量
            long count = countDictItemsByCategoryId(dictCategory.getId());
            dictCategory.setItemCount(count);
        }
        
        return dictCategory;
    }

    @Override
    public Result.PageResult<DictCategory> queryPage(int pageNum, int pageSize, DictCategory dictCategory) {
        QueryWrapper queryWrapper = buildQueryWrapper(dictCategory);
        Page<DictCategory> paginate = dictCategoryMapper.paginate(pageNum, pageSize, queryWrapper);
        
        // 为分页结果中的每个分类统计字典值数量
        for (DictCategory category : paginate.getRecords()) {
            long count = countDictItemsByCategoryId(category.getId());
            category.setItemCount(count);
        }
        
        return new Result.PageResult<>(paginate.getRecords(), paginate.getTotalRow(), pageNum, pageSize);
    }

    @Override
    public int insert(DictCategory dictCategory) {
        validateDictCategory(dictCategory);
        return dictCategoryMapper.insert(dictCategory);
    }

    @Override
    public int update(DictCategory dictCategory) {
        if (dictCategory.getId() == null) {
            throw new IllegalArgumentException("字典分类ID不能为空");
        }
        validateId(dictCategory.getId());
        validateDictCategory(dictCategory);
        
        DictCategory existing = dictCategoryMapper.selectOneById(dictCategory.getId());
        if (existing == null) {
            throw new IllegalArgumentException("字典分类信息不存在");
        }
        
        return dictCategoryMapper.update(dictCategory);
    }

    @Override
    public int deleteById(Long id) {
        validateId(id);
        
        DictCategory existing = dictCategoryMapper.selectOneById(id);
        if (existing == null) {
            throw new IllegalArgumentException("字典分类信息不存在");
        }
        
        return dictCategoryMapper.deleteById(id);
    }

    @Override
    public List<Long> deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        List<Long> successIds = new ArrayList<>();
        List<Long> failedIds = new ArrayList<>();

        for (Long id : ids) {
            try {
                validateId(id);
                
                DictCategory existing = dictCategoryMapper.selectOneById(id);
                if (existing == null) {
                    failedIds.add(id);
                    continue;
                }

                int result = dictCategoryMapper.deleteById(id);
                if (result > 0) {
                    successIds.add(id);
                } else {
                    failedIds.add(id);
                }
            } catch (Exception e) {
                failedIds.add(id);
            }
        }

        if (!successIds.isEmpty()) {
            return successIds;
        } else {
            throw new IllegalArgumentException("批量删除失败");
        }
    }

    /**
     * 验证字典分类信息
     */
    private void validateDictCategory(DictCategory dictCategory) {
        if (dictCategory == null) {
            throw new IllegalArgumentException("字典分类信息不能为空");
        }
        if (StringUtils.isBlank(dictCategory.getName())) {
            throw new IllegalArgumentException("分类名称不能为空");
        }
        if (StringUtils.isBlank(dictCategory.getCode())) {
            throw new IllegalArgumentException("分类代码不能为空");
        }
        // 验证分类代码格式（只能包含字母、数字、下划线）
        if (!dictCategory.getCode().matches("^[a-zA-Z0-9_]+$")) {
            throw new IllegalArgumentException("分类代码只能包含字母、数字、下划线");
        }
    }

    /**
     * 验证ID
     */
    private void validateId(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的字典分类ID");
        }
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper buildQueryWrapper(DictCategory dictCategory) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DictCategory::getId, dictCategory.getId(), dictCategory.getId() != null);
        queryWrapper.like(DictCategory::getName, dictCategory.getName(), StringUtils.isNotEmpty(dictCategory.getName()));
        queryWrapper.like(DictCategory::getCode, dictCategory.getCode(), StringUtils.isNotEmpty(dictCategory.getCode()));
        queryWrapper.like(DictCategory::getDescription, dictCategory.getDescription(), StringUtils.isNotEmpty(dictCategory.getDescription()));
        queryWrapper.eq(DictCategory::getStatus, dictCategory.getStatus(), dictCategory.getStatus() != null);

        queryWrapper.orderBy(DictCategory::getSortOrder, true);
        queryWrapper.orderBy(DictCategory::getName, true);
        queryWrapper.orderBy(DictCategory::getId, true);
        return queryWrapper;
    }
    
    /**
     * 统计指定分类下的字典值数量
     */
    private long countDictItemsByCategoryId(Long categoryId) {
        if (categoryId == null) {
            return 0;
        }
        
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(DictItem::getCategoryId, categoryId);
        return dictItemMapper.selectCountByQuery(queryWrapper);
    }
}